package uk.ac.cam.echo.server;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;

import uk.ac.cam.echo.SafeMessageQueue;
import uk.ac.cam.echo.messages.Message;

/**
 * @author Tom Smith
 */
public class ClientMessageWriter implements Runnable {

	private final Socket m_Socket;
	private final SafeMessageQueue<Message> m_Messages;
		
	/**
	 * Initiate object with the socket to listen on.
	 * @param sock The socket to listen on.
	 * @param messageQueue The message queue to write to the client.
	 */
	public ClientMessageWriter(Socket sock, SafeMessageQueue<Message> messageQueue) {
		this.m_Socket = sock;
		this.m_Messages = messageQueue;
	}
	
	
	@Override
	public void run() {
		try {
			// Output stream for objects to client.
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(this.m_Socket.getOutputStream());
			
			Message m;
			while (true) {
				// take() blocks until a message is available on the SafeMessageQueue.
				m = this.m_Messages.take();
				// Write the message out to the client.
				objectOutputStream.writeObject(m);
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
